<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
/*
 *进云快速开发框架
 **********全局常量说明***********
 * TSTART ：脚本开始时间（精确至微秒）
 * ROOT_D :站点根目录（不以“/”结束）
 * ROOT_AT ：附件根目录（以“/”结束）
 * TIMESTAMP 系统当前时间（精确至秒）
 * BY_JYA 入口标识
 * CLIENT_IP :来访IP
 * AJAX :是否为ajax提交
 * POST :是否为post请求
 * MAXTIMESQL ：sql最大执行时间，超出则通过日志记录相关信息
 * CHARSET ：文件编码
 * FOUNDER ：超级管理员账号
 * COOKIEPRE ：cookie前缀
 * FILEMODE :文件权限码
 * HTTP ：协议头
 * DEVELOP ：是否开启调试模式，调试模式便于修复bug

 **********全局变量说明**********
 * $_AR ：全局引用参数，系统设置参数保存在此变量
 * $_RQ ：全局请求参数，来自get、post、cookie的参数全部保存在里面
*/
if(defined('BY_JYA')){
	exit('bad error');
}
error_reporting(0);
//ini_set('display_errors', '1');
//error_reporting(E_ALL ^ E_NOTICE);
define('TSTART', microtime(true));
define('ROOT_D', str_replace("\\", '/', dirname(dirname(__FILE__))));
define('TIMESTAMP', time());
define('BY_JYA', true);
//加载配置文件
$cfg = ROOT_D . "/core/config.php";
if(!file_exists($cfg)) {
	if(file_exists(ROOT_D . '/install.php')){
		require ROOT_D . '/install.php';
		exit;
	}else{
		header('Content-Type: text/html; charset=utf-8');
		exit('缺少系统核心文件导致无法运行，请联系网站管理员！');
	}
}else{
	require $cfg;
}
//加载常用函数
require ROOT_D . '/core/function/global.php';
require ROOT_D . '/core/function/types.php';
require ROOT_D . '/core/function/pdo.php';
$_AR = $_RQ= array();
 //定义系统全局变量
define('CLIENT_IP', getip());
$ajax=isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
if(!$ajax) {
	$input = file_get_contents("php://input");
	if (!empty($input)){
		$__input = @json_decode($input, true);
		if (!empty($__input)) {
			//如果存在重复，后面会覆盖
			$_RQ = $__input;
			$ajax = true;
		}
	}
	unset($input, $__input);
}
define('AJAX',$ajax);
unset($ajax);
define('POST',$_SERVER['REQUEST_METHOD'] == 'POST');
define('CHARSET',$cfg['setting']['charset']);
define('FILEMODE',$cfg['setting']['filemode']);
define('TABLE_PRE',$cfg['db']['tablepre']);
define('ADDONS', 'addons');
define('RESOURCE', $cfg['dir']['resource']);
define('BASE64_KEY','ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-_');
define('ROOT_AT', ROOT_D .'/'.RESOURCE.'/');
define('ROOT_PLUGIN', ROOT_D .'/'.ADDONS.'/');
define('ROOT_RESOURCE', ROOT_D .'/core/resource/');
//判断是否https，先根据配置文件中的设置（该配置参数的作用为，有些服务器中无法正确获取访问协议，只能手动指定）
define('HTTP',($cfg['setting']['https'] || $_SERVER['SERVER_PORT'] == 443 || (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off'))? 'https://' : 'http://');
if(function_exists('date_default_timezone_set')) {
	date_default_timezone_set($cfg['setting']['timezone']);
}
if(!empty($cfg['setting']['memory_limit']) && function_exists('ini_get') && function_exists('ini_set')) {
	if(@ini_get('memory_limit') != $cfg['setting']['memory_limit']) {
		@ini_set('memory_limit', $cfg['setting']['memory_limit']);
	}
}
if($_SERVER['PHP_SELF']){
	$_AR['siteurl']=HTTP.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']. (empty($_SERVER['QUERY_STRING'])?'':'?') . $_SERVER['QUERY_STRING'];
}else{
	//如果$_SERVER['PHP_SELF']中没有值，则采用此方法
	$_AR['siteurl']=HTTP.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
define('WEB_ROOT',get_web_root());
$_AR['siteroot']=HTTP.$_SERVER['HTTP_HOST'].WEB_ROOT;
define('SITEROOT',$_AR['siteroot']);
header('Content-Type: text/html; charset=' . CHARSET);
//初始化数据库配置
require ROOT_D . '/core/class/db.php';
pdo($cfg['db']);
//初始化插件类数据库接口
require ROOT_D . '/core/class/plugin.php';
tablename($cfg['db']['tablepre'],true);
//初始化系统密钥设置
get_password($cfg['setting']['authkey'],true);
//初始化站长判断函数
is_founder($cfg['setting']['founder']);
error_type();
//获取并整理请求数据
if((function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) || @ini_get('magic_quotes_sybase')) {
	$_GET = istripslashes($_GET);
	$_POST = istripslashes($_POST);
	$_COOKIE = istripslashes($_COOKIE);
}
//解析新型URL格式和自定义URL中的参数
if(defined('IN') && strexists($_SERVER['QUERY_STRING'],'/')){
	$type=(IN=='manage')?1:2;
	$gets=cfc('url_diy')->decode($_SERVER['QUERY_STRING'],$type);
	$gets=links($gets,true);
	if($gets['query']){
		foreach($gets['query'] as $key=>$value){
			$gets[$key]=$value;
		}
	}
	unset($gets['query']);
	$_GET=$gets;
	unset($gets);
}

$cplen = strlen($cfg['cookie']['pre']);
foreach($_COOKIE as $key => $value) {
	if(substr($key, 0, $cplen) == $cfg['cookie']['pre']){
		$_RQ[substr($key, $cplen)] = $value;
	}
}
//将get参数和post参数放到一起，同名的post覆盖get
$_RQ = array_merge($_RQ,$_GET,$_POST);
//用 htmlspecialchars进一步整理用户输入
$_RQ = ihtmlspecialchars($_RQ);
config($cfg);
//优化超级管理员登陆问题
//pdo_update('core_users',array('uniacid'=>1),array('id'=>1,'uniacid'=>0));
//获取系统设置信息
$default=array(
	'session_expire'=>3600,
	'time_ignore'=>5,
	'maxtimesql'=>2,
	'ip_num'=>5,
	'session_num'=>5,
	'template_name'=>'default',
);
$_AR['system']=core_setting('system');
$_AR['system']=check_setting($default,$_AR['system']);
$_AR['system']['session_expire']=$_AR['system']['session_expire']>300?$_AR['system']['session_expire']:300;
//检查是否开启调试模式
if($cfg['setting']['development'] == 1 && (!$_AR['system']['develop_ip'] || $_AR['system']['develop_ip']==CLIENT_IP)){
	define('DEVELOP', 1);
}else{
	if($_AR['system']['development'] == 1 && ($_AR['system']['develop_ip']==CLIENT_IP)){
		define('DEVELOP', 1);
	}else{
		define('DEVELOP', 0);
	}
}
if(DEVELOP){
	ini_set('display_errors', '1');
	error_reporting(E_ALL ^ E_NOTICE);
}
//配置系统主域名
define('DOMAIN',$_AR['system']['domain']);
//检查是否开启分配独立域名
if($_AR['system']['user_domain']){
	define('USER_DOMAIN',true);
	define('DOMAIN_PRE',substr($_AR['system']['domain_pre'],1).WEB_ROOT);
}else{
	define('USER_DOMAIN',false);
}

//设置缓存机制
if(!in_array($cfg['setting']['cache'], array('mysql', 'file', 'memcache'))) {
	$cfg['setting']['cache'] = 'mysql';
}
if($cfg['setting']['cache'] == 'memcache') {
	if (extension_loaded('memcache')) {
		$config = $cfg['setting']['memcache'];
		if (!empty($config['server']) && !empty($config['port'])) {
			$memcacheobj = new Memcache();
			$connect = @$memcacheobj->connect($config['server'], $config['port'], 3);
			if (empty($memcacheobj) || empty($connect)) {
				$cfg['setting']['cache'] = 'mysql';
			}
		} else {
			$cfg['setting']['cache'] = 'mysql';
		}
	} else {
		$cfg['setting']['cache'] = 'mysql';
	}
}
require ROOT_D . '/core/function/cache.'.$cfg['setting']['cache'].'.php';
if($cfg['setting']['cache']=='memcache'){
	cache_memcache($cfg['setting']['memcache']);
}
isetcookie('setconfig',$cfg['cookie']);
//短地址
if($_RQ['p'] && !$_RQ['plugin']){
	$_RQ['plugin']=$_RQ['p'];
}
if($_RQ['a'] && !$_RQ['action']){
	$_RQ['action']=$_RQ['a'];
}
define('IS_ROBOT', cfc('tools')->checkrobot('',$_RQ['isssr']));
//设置、获取session
if(!defined('NOSESSION')){
	if(!defined('IN')){
		if($_RQ['this']){
			define('IN',$_RQ['this']);
		}else{
			define('IN','manage');
		}
		
	}
	//exit(IN);
	$cfg['setting']['session']=!empty($cfg['setting']['session'])?$cfg['setting']['session']:'session';
	$sess = cfc($cfg['setting']['session'],$_AR['system']['session_expire']);
	session_set_save_handler(
		array(&$sess, 'open'),
		array(&$sess, 'close'),
		array(&$sess, 'read'),
		array(&$sess, 'write'),
		array(&$sess, 'destroy'),
		array(&$sess, 'gc')
	);
	register_shutdown_function('session_write_close');
	$session_name=session_name();
	//整理会话ID，如果会话ID没有或者不合法（超过系统规定ID长度）则生成新的会话ID。
	$sid=$_COOKIE[$session_name];
	if(!$sid){
		//找不到sessionID的情况下的处理方法
		$sid=trim($_RQ['ssid']);
		if(strlen($sid)<12){
			$sid='';
		}else{
			$sid=pdo_getcolumn('core_session',array('id'=>$sid),'id');
		}
	}
	if($sid && $_AR['system']['check_ssid']){
		//如果获取到会话ID，则校验会话ID是否合法
		if(substr($sid,16)!=substr(md5(substr($sid,0,16).$cfg['setting']['authkey']),0,10)){
			$sid='';
		}
	}
	if(!$sid){
		do{
			$sid=$cfg['setting']['session_pre'];
			$sid.=random(10);
			$sid.=substr(md5($sid.$cfg['setting']['authkey']),0,10);
			$check=pdo_getcolumn('core_session',array('id'=>$sid),'id');
		}while($check);
	}
	session_id($sid);
	session_start();
	//站点访问频率限制
	if($_SESSION['uniacid'] && $_AR['system']['account_limit']){
		$num=pdo_count('core_access_log',array('createtime'=>TIMESTAMP,'uniacid'=>$_SESSION['uniacid']));
		$limit=pdo_getcolumn('core_account_group',array('id'=>$_SESSION['account']['groupid']),'access');
		if($limit && $num>$limit){
			exi('网站访问太过频繁，请稍后再操作!','error');
		}
	}
	if($_AR['system']['dcc']){
		$_AR['system']['ip_num']=$_AR['system']['ip_num']?$_AR['system']['ip_num']:10;
		$_AR['system']['session_num']=$_AR['system']['session_num']?$_AR['system']['session_num']:100;
		$num=pdo_count('core_session',array('ip'=>CLIENT_IP));
		if($num>$_AR['system']['ip_num'] && !$_SESSION['token']){
			define('NOSESSION',true);
			exi('您的访问被拒绝。如果您是系统管理员，可以修改系统配置，增加同一IP允许的会话数上限！或者关闭系统防cc攻击机制！如无法登陆后台，可以换个IP登陆试试！','error');
		}
		if($_SESSION['timestamp']==TIMESTAMP){
			if($_SESSION['ONESNUM']>=$_AR['system']['session_num']){
				exi('访问太过频繁，请稍后再操作!','error','hold');
			}
			if(!$_SESSION['ONESNUM']){
				$_SESSION['ONESNUM']=1;
			}else{
				$_SESSION['ONESNUM']++;
			}
		}else{
			$_SESSION['timestamp']=TIMESTAMP;
			$_SESSION['ONESNUM']=1;
		}
	}
	if(!$_SESSION['this']){
		$_SESSION['this']=IN;
	}
	//如果开启限制一个账号只能有一个会话，此处检查账户会话是否有效
	if($_AR['system']['login_one'] && $_SESSION['uid'] && $_SESSION['this']=='manage'){
		$user_ssid=pdo_getcolumn('core_users',array('id'=>$_SESSION['uid']),'ssid');
		$now_ssid=session_id();
		if($user_ssid != $now_ssid){
			//会话被挤出
			$_SESSION['uid']=0;
			$_SESSION['access']=array();
			exi('您的账号在另一个地方登陆，您被迫下线！如果不是您本人操作，您的账号可能已被盗！请及时修改密码！如需重新登陆，请刷新页面！','error',links('core/user.logout/'));
		}
	}
	//获取上级uid
	if($_RQ['fromuser']){
		$_SESSION['fromuser']=intval($_RQ['fromuser']);
		//如果已经登录，就设置上下级关系
		if($_SESSION['uid']){
			publish('core','member.setfromuser',array('mid'=>$_SESSION['uid']));
		}
	}elseif($_RQ['room_id']){//来自直播间
		$wxgid=$_SESSION['wxapp_id']?:intval($_RQ['wxgid']);
		if($_RQ['share_openid']){//来自分享卡片
			$fromuser=pdo_getcolumn('core_fans',array('openid'=>$_RQ['share_openid'],'uniacid'=>$_SESSION['uniacid'],'wxgid'=>$wxgid),'mid');
		}else{//直播间
			$live_id=pdo_getcolumn('core_account_wxapp_live',array('wxapp_id'=>$wxgid,'uniacid'=>$_SESSION['uniacid']),'id');
			$fromuser=pdo_getcolumn('core_account_wxapp_live_rooms',array('roomid'=>$_RQ['room_id'],'live_id'=>$live_id,'uniacid'=>$_SESSION['uniacid']),'mid');
		}
		$_SESSION['fromuser']=intval($fromuser);
	}
	//定义access
	define('ACCESS_PLUGIN',$_RQ['plugin']?:'core');
	define('ACCESS_ACTION',$_RQ['action']?:'');
	//获取客户端信息
	if($_RQ['ssid'] || ($_RQ['os'] && $_SESSION['os']!=$_RQ['os']) || ($_RQ['fromapp'] && $_SESSION['fromapp']!=$_RQ['fromapp']) || !$_SESSION['os'] || !$_SESSION['container'] || !$_SESSION['terminal']){
		require ROOT_D . '/core/class/agent.php';
		//判断本次访问来自何处！
		$_SESSION['fromapp']=$_RQ['fromapp'];
		if($_RQ['os']){
			$_SESSION['os']=trim($_RQ['os']);
		}elseif($_SESSION['os']!='ttapp' && $_SESSION['os']!='aliapp' && $_SESSION['os']!='baiduapp'){
			$_SESSION['os'] = Agent::deviceType();
			if($_SESSION['os'] == Agent::DEVICE_MOBILE){
				$_SESSION['os'] = 'mobile';
			}elseif($_SESSION['os'] == Agent::DEVICE_DESKTOP) {
				$_SESSION['os'] = 'windows';
			}else{
				$_SESSION['os'] = 'windows';
			}
		}
		if($_SESSION['os']=='wxapp'){
			$_SESSION['container']='wxapp';
		}elseif($_SESSION['os']=='ttapp'){
			$_SESSION['container']='ttapp';
		}elseif($_SESSION['os']=='aliapp'){
			$_SESSION['container']='aliapp';
		}elseif($_SESSION['os']=='baiduapp'){
			$_SESSION['container']='baiduapp';
		}else{
			$_SESSION['terminal'] = Agent::browserType();
			if ($_SESSION['terminal'] == Agent::BROWSER_TYPE_ANDROID) {
				$_SESSION['terminal'] = 'android';
			} elseif ($_SESSION['terminal'] == Agent::BROWSER_TYPE_IPAD) {
				$_SESSION['terminal'] = 'ipad';
			} elseif ($_SESSION['terminal'] == Agent::BROWSER_TYPE_IPHONE) {
				$_SESSION['terminal'] = 'iphone';
			} elseif ($_SESSION['terminal'] == Agent::BROWSER_TYPE_IPOD) {
				$_SESSION['terminal'] = 'ipod';
			} else {
				$_SESSION['terminal'] = 'unknown';
			}
			if(Agent::isMicroWorkMessage() == Agent::MICRO_WXWORK_YES) {
				$_SESSION['container'] = 'wxwork';
			}elseif(Agent::isMicroMessage() == Agent::MICRO_MESSAGE_YES) {
				$_SESSION['container'] = 'wechat';
			}
			if(strexists($_SERVER['HTTP_USER_AGENT'],'Alipay')){
				$_SESSION['container']='alipay';
			}
			if(Agent::isToutiaoMicroApp() == Agent::MICRO_TOUTIAO_YES) {
				$_SESSION['container'] = 'ttapp';
				$_SESSION['os']='ttapp';
			}
		}
	}
}
//读取系统附件配置
$core_attachment=core_setting('attachment');
if(!$core_attachment || !$core_attachment['type']){
		$core_attachment=array('type'=>0,'attachment_url'=>'../'.RESOURCE.'/');
		define('ATTACHMENT_ROOTTYPE',0);
		define('ATTACHMENT_ROOTURL',SITEROOT.RESOURCE.'/');
}else{
		define('ATTACHMENT_ROOTTYPE',$core_attachment['type']);
		define('ATTACHMENT_ROOTURL',$core_attachment['attachment_url']);
}
//站点附件
$uni_attachment=uni_setting('attachment');
if($uni_attachment['type']>0){
		$_AR['attachment']=$uni_attachment;
		define('IS_UNI_ATTACHMENT',1);
		define('ATTACHMENT_TYPE',$_AR['attachment']['type']);
		define('ATTACHMENT_URL',$_AR['attachment']['attachment_url']);
}else{
		$_AR['attachment']=$core_attachment;
		define('IS_UNI_ATTACHMENT',0);
		define('ATTACHMENT_TYPE',ATTACHMENT_ROOTTYPE);
		define('ATTACHMENT_URL',ATTACHMENT_ROOTURL);
}
unset($cfg);
//站点关闭、禁止访问，针对已登录的非超级管理员
if($_SESSION['uid'] && !$_SESSION['isfounder']){
	
	if($_AR['system']['close']){
		session_destroy();
		echo '站点已关闭，关闭原因：' . $_AR['system']['close_reason'];
		exit;
	}
	if($_SESSION['user']['status'] == 1){
		//session_destroy();
		//exit('您的账号正在审核或是已经被系统禁止，请联系网站管理员解决！');
	}
}
